package yns.springboot.security.sample.security.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import yns.springboot.security.sample.dao.RoleDao;
import yns.springboot.security.sample.dao.UserDao;
import yns.springboot.security.sample.dto.RoleDto;
import yns.springboot.security.sample.entity.RoleEntity;
import yns.springboot.security.sample.entity.UserEntity;
import yns.springboot.security.sample.security.service.SystemUserDetailService;


@Service
public class SystemUserDetailServiceImpl implements SystemUserDetailService {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private RoleDao roleDao;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		logger.info("username : " + username);
		UserEntity userEntity = userDao.getUserByName(username);
		
		if (userEntity == null) {
			throw new UsernameNotFoundException("用户不存在");
		}
		
		logger.info(userEntity.toString());
		
		String loginName = userEntity.getUserName();
		String loginPwd = userEntity.getUserPwd();
		int roleID = userEntity.getRoleID();
		
		RoleEntity roleEntity = roleDao.getRoleByID(roleID);
		RoleDto roleDto = new RoleDto();
		BeanUtils.copyProperties(roleEntity, roleDto);
		
		logger.info(roleDto.toString());
		
		List<GrantedAuthority> authorities = getAuthorities(roleDto);
		
		User user = new User(loginName, loginPwd, authorities);
		
		return user;
	}
	
	private List<GrantedAuthority> getAuthorities(RoleDto roleDto){
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		
		String[] authority = roleDto.getAuthorityName().split(",");
		
		for (int i = 0; i < authority.length; i++) {
			authorities.add(new SimpleGrantedAuthority(roleDto.buildAuthorityName(authority[i])));
		}

		return authorities;
	}

}
